package com.hzit.manager.controller;

import com.hzit.common.util.R;
import com.hzit.manager.client.UserClient;
import com.hzit.manager.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.net.URI;


@RestController
@RequestMapping("/rest")
public class RestTemplateController {
	@Autowired
	private RestTemplate restTemplate;
	private static final String USER_SERVICE = "hzit-user";
	/**
	 *  <dependency>
	 *      <groupId>org.springframework.cloud</groupId>
	 *      <artifactId>spring-cloud-starter-loadbalancer</artifactId>
	 *  </dependency>
	 *  注意：要使用下面的负载远程组件必须要添加上面的依赖
	 */
	@Autowired
	LoadBalancerClient loadBalancerClient;      // 引入负载均衡组件
	@Autowired
	private UserClient userClient;

	//1. 查询所有用户列表 (restTemplate来调用远程服务)
	@GetMapping("/user/list")
	public R findUsers(){
		ServiceInstance instance = loadBalancerClient.choose(USER_SERVICE);  // 参数：微服务在nacos中注册的名字
		// ResponseEntity<R> entity = restTemplate.getForEntity(instance.getUri() + "/user/list", R.class);
		//或者使用(参数1：请求uri地址 参数2：请求类型 参数3：请求体 参数4：响应体类型)
		ResponseEntity<R> exchange = restTemplate.exchange(instance.getUri() + "/user/list", HttpMethod.GET, null, R.class);
		return exchange.getBody();
	}

	//2. 查询 (restTemplate来调用远程服务)
	@GetMapping("/user/findById")
	public R findUserbyId(){
		ServiceInstance instance = loadBalancerClient.choose("hzit-user");
		User user = restTemplate.getForObject(instance.getUri() + "/user/findById", User.class);
		return R.ok(user);
	}

	//3. 查询单个用户(openFeign调用实现)
	@GetMapping("/user/findById2")
	public R findByUser2(){
		return R.ok(userClient.findById());
	}
}
